package com.orchard.orchardfarmmanagementsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orchard.orchardfarmmanagementsystem.dto.EvaluationDTO;
import com.orchard.orchardfarmmanagementsystem.entity.Evaluation;
import com.orchard.orchardfarmmanagementsystem.mapper.EvaluationMapper;
import com.orchard.orchardfarmmanagementsystem.service.EvaluationService;
import com.orchard.orchardfarmmanagementsystem.utils.Result;
import com.orchard.orchardfarmmanagementsystem.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


@Service
public class EvaluationServiceImpl extends ServiceImpl<EvaluationMapper, Evaluation> implements EvaluationService {

    @Autowired
    private EvaluationMapper evaluationMapper;



    @Transactional
    public Result submitTaskEvaluation(Integer taskId, EvaluationDTO evaluationDTO) {
        if (taskId == null || evaluationDTO == null) {
            return Result.error(50001, "参数不能为空");
        }

        try {
            // 参数验证
            if (evaluationDTO.getRating() == null && evaluationDTO.getComment() == null) {
                return Result.error(50001, "评分或评论至少需要填写一项");
            }

            // 查询现有评价
            Evaluation existingEvaluation = evaluationMapper.selectOne(new QueryWrapper<Evaluation>().eq("task_id", taskId));

            // 创建或更新评价实体并复制属性
            Evaluation evaluation = new Evaluation();
            BeanUtils.copyProperties(evaluationDTO, evaluation);
            evaluation.setTaskId(taskId);
            evaluation.setUserId(UserHolder.getUser().getUserId());
            evaluation.setUpdatedAt(LocalDateTime.now());

            if (existingEvaluation != null) {
                // 如果评价已存在，则更新
                evaluation.setEvaluationId(existingEvaluation.getEvaluationId()); // 设置ID以便于更新
                evaluation.setCreatedAt(existingEvaluation.getCreatedAt()); // 保持原始创建时间
                int updateResult = evaluationMapper.updateById(evaluation);
                if (updateResult <= 0) {
                    return Result.error(50001, "更新评价失败");
                }
                return Result.success("更新评价成功", evaluation);
            } else {
                // 如果评价不存在，则插入新记录
                evaluation.setCreatedAt(LocalDateTime.now());
                int insertResult = evaluationMapper.insert(evaluation);
                if (insertResult <= 0) {
                    return Result.error(50001, "插入评价失败");
                }
                return Result.success("插入评价成功", evaluation);
            }

        } catch (Exception e) {
            // 记录异常日志
            return Result.error(50001, "系统错误，请稍后再试");
        }
    }
}
